import { defineStore, storeToRefs } from 'pinia'
import { ref } from 'vue'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import { useSocketStore } from '@/stores/socketStore'
import { useCurrActStroe } from '@/stores/currActStore'
import useUrtToImg from '@/utils/urlToImg'

import type { MsgLogs, MsgLogsDate, MsgLogsDateArr, UserTarget } from '@/types/loginType'
export const useMessageStore = defineStore('useMessageStore', () => {
  const { socket } = useSocketStore()

  const logsData = ref<MsgLogsDateArr>({})
  // 获取对应于用户下的历史记录
  // const logsData = ref<MsgLogs[]>([])

  socket.on('pushMsg', (data) => {
    const time = new Date().toLocaleTimeString().substring(0, 5)
    addLogsData({ time, ...data })
  })

  // 修改方法
  function assignLogsData(data: MsgLogsDateArr) {
    for (const [key, value] of Object.entries(data)) {
      data[key] = value.map((item) => {
        const { content, ...msgData } = item
        const p = urtToImg(content as string)
        return { content: p, ...msgData }
      })
    }
    logsData.value = data
  }
  // 添加方法
  function addLogsData(data: MsgLogs) {
    // 添加至当天
    const date = new Date().toLocaleDateString()
    const { content, ...msgData } = data
    const p = urtToImg(content as string)
    if (logsData.value[date]) {
      logsData.value[date].push({ content: p, ...msgData })
    } else {
      logsData.value[date] = []
      logsData.value[date].push({ content: p, ...msgData })
    }
  }

  // 转换方法
  function urtToImg(content: string) {
    const regex = /https?:\/\/[^\s]+(\.jpg|\.jpeg|\.png|\.gif|\.bmp|\.webp)/gi
    const urlArr = content.match(regex)
    if (urlArr) {
      for (let i = 0; i < urlArr.length; i++) {
        const imgElement = new Image()
        imgElement.src = urlArr[i]
        const { setWidth } = useUrtToImg()
        const [width, height] = setWidth(imgElement, 200)
        imgElement.width = width
        imgElement.height = height
        const imgText = imgElement.outerHTML
        content = content.replace(urlArr[i], imgText)
      }
    }
    return content
  }
  //
  async function getLogsData(userId: string) {
    const { getMessageLogs } = useAsyncAxios()
    const { currUser } = storeToRefs(useCurrActStroe())
    const { status, data } = await getMessageLogs(currUser.value.id, userId)
    if (status === 200) {
      //
      const result = data as MsgLogsDate

      const resultLogsData = Object.entries(result).reduce<MsgLogsDateArr>((acc, [date, logs]) => {
        const formattedDate = new Date(date).toLocaleDateString()
        if (!acc[formattedDate]) {
          acc[formattedDate] = []
        }
        const formattedLogs = {
          ...logs,
          time: new Date(logs.time).toLocaleTimeString().substring(0, 5)
        }
        acc[formattedDate].push(formattedLogs)
        return acc
      }, {})
      assignLogsData(resultLogsData as MsgLogsDateArr)
    }
  }

  // 当前选择用户
  const userTarget = ref<UserTarget>({ id: '', name: '', img: '' })
  // 修改方法
  function changeUserTarget(target: UserTarget) {
    userTarget.value = target
  }

  //

  return {
    userTarget,
    logsData,
    getLogsData,
    assignLogsData,
    addLogsData,
    changeUserTarget
  }
})
